﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using AutoUpdater.Properties;
using System.Runtime.InteropServices;

namespace AutoUpdater
{
    static class Program
    {

        ///<summary>
        /// 该函数设置由不同线程产生的窗口的显示状态
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表，请查阅ShowWlndow函数的说明部分</param>
        /// <returns>如果函数原来可见，返回值为非零；如果函数原来被隐藏，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);


        /// <summary>
        ///  该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        /// <summary>
        /// 说明：
        /// OAUS使用的是免费版的通信框架ESFramework，最多支持10个人同时在线更新。如果要突破10人限制，请联系 www.oraycn.com
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(ConfigurationManager.AppSettings["CurrentLanguage"]);
                
                string serverIP = ConfigurationManager.AppSettings["ServerIP"];
                int serverPort = int.Parse(ConfigurationManager.AppSettings["ServerPort"]);               
                string callBackExeName= ConfigurationManager.AppSettings["CallbackExeName"];
                string title = ConfigurationManager.AppSettings["Title"];     
                string processName = callBackExeName.Substring(0, callBackExeName.Length - 4);
                //bool haveRun = ESBasic.Helpers.ApplicationHelper.IsAppInstanceExist(processName);
                //if (haveRun)
                //{
                //    MessageBox.Show(Resources.TargetIsRunning);                   
                //    return;
                //}
                try
                {
                    MainForm form = new MainForm(serverIP, serverPort, callBackExeName, title);
                    Application.Run(form);
                }
                finally
                {
                    try
                    {
                        ESBasic.Helpers.ApplicationHelper.ReleaseAppInstance(processName);
                        DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                        string callBackPath = dir.FullName + "\\" + callBackExeName; //自动升级完成后，要启动的exe的完整路径。（1）被分发的程序的可执行文件exe必须位于部署目录的根目录。（2）OAUS的客户端（即整个AutoUpdater文件夹)也必须位于这个根目录。
                        if (File.Exists(callBackPath))
                        {
                            System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(callBackPath);
                            ShowWindowAsync(myProcess.MainWindowHandle, 1);//显示
                            SetForegroundWindow(myProcess.MainWindowHandle);//当到最前端
                        }
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show(ee.Message);
                    }
                }
            }
            catch (Exception ee)
            {
            }
        }

     
    }
}
